<template>
    <div class="warpper">
        <el-card>
            <el-alert title="只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
            <el-row class="cat_opt">
                <el-col>
                    <span class="selectLabel">请选择商品分类：</span>
                    <el-cascader 
                    v-model="selectClass" 
                    :options="cateList"
                    :props="cateProps"
                    size="small"
                    @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>

            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <template>
                        <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="addParamsDialog = true">添加参数</el-button>
                        <el-table 
                        :data="manyData"
                        style="width: 100%"
                        border
                        stripe>
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag 
                                    :key="i" 
                                    v-for="(item, i) in scope.row.attr_vals"
                                    type="primary" 
                                    closable
                                    size="small"
                                    @close='closeTag(i, scope.row)'>
                                        {{item}}
                                    </el-tag>
                                    <el-input
                                    class="input-new-tag"
                                    v-if='scope.row.inputTagVisible'
                                    v-model="scope.row.inputTagValue"
                                    ref="saveTagInput"
                                    size='mini'
                                    @keyup.enter.native='$event.target.blur'
                                    @blur='handleInputConfirm(scope.row)'></el-input>
                                    <el-button v-else class="button-new-tag" size='mini' @click='showTagInput(scope.row)'>+ New Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="ID"></el-table-column>
                            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button type="primary" icon="el-icon-edit" size="small" @click="editParams(scope.row.attr_id)">编辑</el-button>
                                    <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteParamsConfirm(scope.row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <template>
                        <el-button type="primary" size="small" :disabled="isBtnDisabled" @click='addParamsDialog = true'>添加属性</el-button>
                        <el-table 
                        :data="onlyData"
                        style="width: 100%"
                        border
                        stripe>
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag 
                                    :key="i" 
                                    v-for="(item, i) in scope.row.attr_vals"
                                    type="primary" 
                                    closable
                                    size="small"
                                    @close='closeTag(i, scope.row)'>
                                        {{item}}
                                    </el-tag>
                                    <el-input
                                    class="input-new-tag"
                                    v-if='scope.row.inputTagVisible'
                                    v-model="scope.row.inputTagValue"
                                    ref="saveTagInput"
                                    size='mini'
                                    @keyup.enter.native='$event.target.blur'
                                    @blur='handleInputConfirm(scope.row)'></el-input>
                                    <el-button v-else class="button-new-tag" size='mini' @click='showTagInput(scope.row)'>+ New Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="ID"></el-table-column>
                            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button type="primary" icon="el-icon-edit" size="small" @click="editParams(scope.row.attr_id)">编辑</el-button>
                                    <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteParamsConfirm(scope.row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-dialog
        :title='"添加" + titleText'
        :visible.sync='addParamsDialog'
        width="60%">
            <el-form
            :model='addParamsForm'
            :rules='addParamsRules'
            ref='addParamsForm'
            label-width='6rem'>
                <el-form-item :label='titleText' prop='attr_name'>
                    <el-input v-model="addParamsForm.attr_name" placeholder='请输入所需添加的参数名称'></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddParamsDialog">取 消</el-button>
                <el-button type='primary' @click="addParams()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
        :title='"修改" + titleText'
        :visible.sync='editParamsDialog'
        width="60%">
            <el-form
            :model='editParamsForm'
            :rules='editParamsRules'
            ref='editParamsForm'
            label-width='6rem'>
                <el-form-item :label='titleText' prop='attr_name'>
                    <el-input v-model="editParamsForm.attr_name" placeholder='请输入所需修改的参数名称'></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editParamsDialog = false">取 消</el-button>
                <el-button type='primary' @click="setParams()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                selectClass: [],
                cateList: [],

                // tabs-pane active change
                activeName: 'many',
                manyData: [],
                onlyData: [],
                addParamsDialog: false,
                editParamsDialog: false,

                // cascader options
                cateProps: {
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                    checkStrictly: true,
                    expandTrigger: 'hover'
                },

                // tree table 指定每列定义
                columns: [
                    {
                        label: '参数名称',
                        prop: ''
                    },
                    {
                        label: '操作',
                        type: 'template',
                        template: 'operation'
                    }
                ],

                addParamsForm: {
                    attr_name: ''
                },
                addParamsRules: {
                    attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
                },

                editParamsForm: {
                    attr_name: ''
                },
                editParamsRules: {
                    attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
                }
            }
        },

        created() {
            this.getCateList()
        },

        methods: {
            async getCateList() {
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status === 200) {
                    this.cateList = res.data
                }
            },

            async getAttributes() {
                const { data: res } = await this.$http.get(`/categories/${this.cateID}/attributes`, { params: { sel: this.activeName } })
                if (res.meta.status == 200) {
                    res.data.forEach(item => {
                        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                        item.inputTagVisible = false
                        item.inputTagValue = ''
                    })
                    this.manyData = this.activeName == 'many' ? res.data : []
                    this.onlyData = this.activeName == 'only' ? res.data : []
                } else {
                    this.$message.error('Faild get params data', { showClose: true })
                }
            },

            handleChange() {
                this.selectClass = this.selectClass.length < 3 ? [] : this.selectClass 
                this.tirggerGet()
                this.onlyData = []
                this.manyData = []
            },

            handleTabClick() {
                this.tirggerGet()
            },

            // 判断是否获取参数/属性
            tirggerGet() {
                if (!this.isBtnDisabled) {
                    this.getAttributes()
                } else {
                    this.$message.info('未选中第三级分类', { showClose: true })
                }
            },

            // 控制标签
            closeTag(i, row) {
                this.$confirm('是否删除' + row.attr_vals[i] + '标签？', '删除标签', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    row.attr_vals.splice(i, 1)
                    this.updateAttributes(row)
                }).catch(() => {
                    this.$message.info('已取消删除', { showClose: true })
                })
            },
            handleInputConfirm(row) {
                if (row.inputTagValue.trim().length != 0) {
                    row.attr_vals.push(row.inputTagValue)
                } 
                row.inputTagValue = ''
                row.inputTagVisible = false
                this.updateAttributes(row)
            },
            showTagInput(row) {
                row.inputTagVisible = true
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus()
                })
            },
            async updateAttributes(row) {
                    const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: this.activeName,
                    attr_vals: row.attr_vals.join(',')
                })
                if (res.meta.status === 200) {
                    this.$message.success('Successful update tag')
                } else {
                    this.$message.error('Failed update tag')
                }
            },

            // 添加参数
            addParams() {
                this.$refs.addParamsForm.validate(async valid => {
                    if (valid) {
                        await this.$http.post(`categories/${this.cateID}/attributes`, {
                            attr_name: this.addParamsForm.attr_name,
                            attr_sel: this.activeName
                        }).then(res => {
                            if (res.data.meta.status !== 201) {
                                this.$message.error('Failed add params', { showClose: true })
                                this.addParamsForm.attr_name = ''
                            } else {
                                this.$message.success('Successful add params')
                            }
                        }).catch(() => {
                            this.$message.error('Connection failed', { showClose: true })
                        })
                        this.addParamsDialog = false
                        this.$refs.addParamsForm.resetFields()
                        this.getAttributes()
                    }
                })
            },
            closeAddParamsDialog() {
                this.$refs.addParamsForm.resetFields()
                this.addParamsDialog = false
            },

            async editParams(attr_id) {
                // this.editParamsForm = scope
                const { data: res } = await this.$http.get(`categories/${this.cateID}/attributes/${attr_id}`, {
                    params: {
                        attr_sel: this.activeName
                    }
                })
                if (res.meta.status === 200) {
                    this.editParamsForm = res.data
                } else {
                    this.$message.error('获取参数信息失败')
                }
                this.editParamsDialog = true
            },
            setParams() {
                this.$refs.editParamsForm.validate(async valid => {
                    if (valid) {
                        const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${this.editParamsForm.attr_id}`, {
                            attr_name: this.editParamsForm.attr_name,
                            attr_sel: this.activeName
                        })
                        if (res.meta.status === 200) {
                            this.$message.success('参数更新成功')
                        } else {
                            this.$message.error('参数更新失败')
                        }
                    }
                })
                this.editParamsDialog = false
                this.$refs.editParamsForm.resetFields()
                this.getAttributes()
            },
            closeeditParamsDialog() {
                this.$refs.editParamsForm.resetFields()
                this.editParamsDialog = false
            },

            deleteParamsConfirm(attr_id) {
                this.$confirm('是否删除该参数？', '删除参数', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteParams(attr_id)
                }).catch(() => {
                    this.$message.info('已取消删除参数')
                })
            },
            async deleteParams(attr_id) {
                await this.$http.delete(`categories/${this.cateID}/attributes/${attr_id}`).then(() => {
                    this.getAttributes()
                    this.$message.success('Successful delete params')
                }).catch(() => {
                    this.$message.error('Failed delete params')
                })
            }
        },

        computed: {
            isBtnDisabled() {
                if (this.selectClass < 3) {
                    return true
                } else {
                    return false
                }
            },

            cateID() {
                if (this.selectClass.length == 3) {
                    return this.selectClass[2]
                } else {
                    return null
                }
            },

            titleText() {
                return this.activeName === 'many' ? '动态参数' : '静态属性'
            }

            // ipaddrArray(str) {
            //     console.log(str)
            //     return str.split(',')
            // }
        }
    }
</script>

<style lang="less" scoped>
    .treeTab,
    .pagination{
        margin-top: 1rem;
        font-size: .75rem;
    }
    .el-cascader{
        width: 16rem;
    }
    .el-table{
        margin-top: 1rem;
    }
    .el-tag{
        margin-right: .5rem;
    }
    .selectLabel{
        margin-left: .5rem;
        font-size: .75rem;
    }
    .cat_opt{
        margin-bottom: .5rem;
    }
    .input-new-tag{
        margin: .2rem;
        height: 1.5rem;
        line-height: 1.25rem;
        width: 6rem;
        vertical-align: bottom;
    }
    .button-new-tag{
        height: 1.75rem;
        line-height: 1.85rem;
        padding-top: 0;
        padding-bottom: 0;
    }
</style>